import Const from './const'

function Util () {
  return {
    sprintf: require('locutus/php/strings/sprintf'),
    date: require('locutus/php/datetime/date'),
    trim: require('locutus/php/strings/trim'),
    parseDate: parseDate,
    clearData: clearData,
    is: is,
    clone: clone,
    time: time,
    convertMoney: convertMoney,
    formatMoney: formatMoney,
    get: get,
    digitLength: digitLength,
    imgUrl: imgUrl
  }

  function parseDate (date) {
    return parseInt(new Date(date).getTime() / 1000)
  }

  function clearData (data) {
    Object.keys(data).forEach(function (key) {
      if (is('object', data[key])) {
        data[key] = {}
      }
      if (is('array', data[key])) {
        data[key] = []
      }
      if (is('number', data[key])) {
        data[key] = 0
      }
      if (is('string', data[key])) {
        data[key] = ''
      }
    })
  }

  function is (type, obj) {
    let item
    item = Object.prototype.toString.call(obj).slice(8, -1)
    return obj !== undefined && obj !== null && item.toLowerCase() === type.toLowerCase()
  }

  function clone (obj) {
    let o
    if (typeof obj === 'object') {
      if (obj === null) {
        o = null
      } else {
        if (obj instanceof Array) {
          o = []
          for (let i = 0, len = obj.length; i < len; i++) {
            o.push(clone(obj[i]))
          }
        } else {
          o = {}
          for (let j in obj) {
            o[j] = clone(obj[j])
          }
        }
      }
    } else {
      o = obj
    }
    return o
  }

  function time () {
    return parseInt(new Date().getTime() / 1000, 10)
  }

  function convertMoney (money) {
    if (!money) {
      return 0
    }
    return parseInt(money) * 100
  }

  function formatMoney (money) {
    if (!money) {
      return '0.00'
    }

    return this.sprintf('%.2f', money / 100);
  }

  function get (obj, key) {
    return key.split('.').reduce(function (o, x) {
      return (typeof o === 'undefined' || o === null) ? o : o[x]
    }, obj)
  }

  function digitLength (data, length) {
    return this.sprintf('%0' + length + 'd', data)
  }

  function imgUrl (img) {
    if (!img) {
      return ''
    }
    if (img.indexOf('http') >= 0) {
      return img
    }
    return Const.NET.FILE_STATIC_URL + img
  }
}

export default new Util()
